from langchain_openai import ChatOpenAI
import asyncio
from browser_use import Agent, Browser
from playwright.async_api import BrowserContext
import get_info
import llm_settings

browser = Browser()

llm = ChatOpenAI(
    api_key=llm_settings.api_key,
    base_url=llm_settings.base_url,
    model=llm_settings.model
)




async def wait_for_ifrun():
    while True:
        try:
            with open("ifrun.txt", "r") as f:
                content = f.read().strip()
                if content == "1":
                    return
        except FileNotFoundError:
            pass
        await asyncio.sleep(1)  # 每隔1秒检查一次

async def wait_for_flag():
    while True:
        try:
            with open("flag.txt", "r") as f:
                content = f.read().strip()
                if content == "1":
                    return
        except FileNotFoundError:
            pass
        await asyncio.sleep(1)  # 每隔1秒检查一次

async def main():
    # 创建一个新的 BrowserContext
    async with await browser.new_context() as context:
        await wait_for_ifrun()
        useraccount, userpassword = get_info.get_acc()
        agent = Agent(
            task="使用opentab打开steam官方网站然后点击登录，输入账号：" + useraccount + " 密码:" + userpassword+" 当出现和电子邮件相关的内容后结束代码",
            llm=llm,
            browser=browser,
            browser_context=context
        )
        result = await agent.run()

        # 等待 flag.txt 文件内容变为 "1"
        await wait_for_flag()
        # Pass the context to the next agent
        usercaptcha = get_info.get_catpcha()
        agent2 = Agent(
            llm=llm,
            browser=browser,
            browser_context=context,
            task="输入邮箱验证码" + usercaptcha +" 输入完成后如果页面上出现社区或者商店链接则结束代码"
        )
        result = await agent2.run()
        with open("ifrun.txt", "w") as f:
            f.write("0")
        with open("flag.txt", "w") as f:
            f.write("0")
        print(result)
        input("输入回车关闭浏览器！")
        await browser.close()
if __name__ == "__main__":
    asyncio.run(main())